package nciae.db.conf;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import nciae.db.pojo.entity.Student;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    //密钥
    private static final String SECRET_KEY = "water102";
    // 过期时间，s为单位
    private static final long EXPIRATION = 14400l;// 4個小時

    public static String createToken(Student user){
        Date expiredDate = new Date(System.currentTimeMillis()+EXPIRATION*1000);
        Map<String,Object> map = new HashMap<>();
        // 设置jwt的头部信息
        // alg:加密算法，typ:token的类型
        map.put("alg","HS256");
        map.put("typ","JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("id",user.getId())
                .withClaim("tel",user.getTel())
                .withClaim("name",user.getName())
                .withClaim("dep",user.getDepartment())
                .withClaim("classid",user.getClassId())
                .withClaim("projectid",user.getProjectId())
                .withExpiresAt(expiredDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET_KEY));
        return token;
    }

    public static Map<String, Claim> verifyToken(String token){
        DecodedJWT jwt = null;
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).build();
            jwt = verifier.verify(token);

        }catch (Exception e){
            System.out.println("token解析异常");
            return null;
        }
        return jwt.getClaims();
    }

}

